package com.demo.woziqi.server;

import com.demo.woziqi.util.GameConstant;
import com.demo.woziqi.GameFightStage;
import com.demo.woziqi.message.Message;
import javafx.application.Platform;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @Author 宋明松
 * @Version V1.0.0
 * @Date 2022-05-24
 * <p>
 * 服务器端线程
 */
public class GameThread implements Runnable {
    public static ServerSocket serverSocket; // TCP/IP 服务器端线程启动
    private GameFightStage gameFightStage;

    public GameThread(GameFightStage gameFightStage){
        this.gameFightStage = gameFightStage;
    }

    @Override
    public void run() {
        try {
            serverSocket = new ServerSocket(GameConstant.WDkText);
        } catch (IOException e) {
            GameConstant.threadServerRun = false;
            e.printStackTrace();
        }
        while (GameConstant.serverSocketIsClosed) { // GameConstant.serverSocketIsClosed==true ,表示socket没有关闭
            Socket socket = null; // 阻塞，等待客户端发送请求
            InputStream is = null;
            ObjectInputStream ois=null;
            try {
                socket = serverSocket.accept();
                is = socket.getInputStream();
                ois = new ObjectInputStream(is);
                Message message= (Message) ois.readObject();
                Platform.runLater(() -> { // 页面节点刷新方法
                    gameFightStage.processMessage(message); // 调用方法处理接收的Message
                });
            } catch (Exception e) {
                GameConstant.threadServerRun = false; // 服务器端启动时报
            }
            finally {
                try {
                    if (ois != null||is!=null){
                        ois.close(); // 关闭资源占用
                        is.close();
                    }
                } catch (IOException e) {
                }
            }
        }
    }
}
